import _ from 'lodash'
import ebus from 'libs/ebus.js'
import {http, systemApi, storageApi} from '../../api.js'
import * as types from '../mutation-types'

export function getPlatformInfo({dispatch}, cb) {
  http('/api/platform/cfg', 'GET').then(function(res) {
    if (res && res.data && res.data.code === 0) {
      dispatch(types.SET_PLATFORM, res.data.data)
      cb && cb.success && cb.success()
    } else {
      cb && cb.error && cb.error(res.data)
    }
  }, function(res) {
    cb && cb.noResponse && cb.noResponse()
  })
}

export function tryLogin({dispatch}, req, cb) {
  http('/api/auth/login', 'POST', req, {timeout: 2000}).then(function(res) {
    if (res && res.data && res.data.code === 0) {
      let client = res.data.data
      if (client) {
        dispatch(types.SET_AUTH_CLIENT, client)
      }
      dispatch(types.SET_AUTH_USERNAME, req.username)
      dispatch(types.SET_AUTH_REQ, req)
      dispatch(types.SET_AUTHED, true)
      cb && cb.success && cb.success()
    } else {
      cb && cb.error && cb.error(res.data)
    }
  }, function(res) {
    cb && cb.noResponse && cb.noResponse()
  })  
}

export function doLogout({dispatch}) {
  dispatch(types.SET_AUTH_USERNAME, '')
  dispatch(types.SET_AUTH_CLIENT, {})
  dispatch(types.SET_AUTHED, false)
}

export function loadSystemState({dispatch, state}, {init = false} = {}) {
  if (init && state.system.state.init) {
    return
  }
  systemApi.getState().then(function(res) {
    if (res && res.data && res.data.code === 0) {
      dispatch(types.SET_LICENSE_INFO, res.data.data._info.licenseInfo)
    }
  }.bind(this))
}

//user
export function doLoadUsers({dispatch}) {
  dispatch(types.REFRESH_USERS_START)
  http('/api/auth/users', 'GET').then(function(res) {
    if (res && res.data && res.data.code === 0) {
      dispatch(types.SET_USERS, res.data.data.users)
    }
    dispatch(types.REFRESH_USERS_END)
  })
}

export function setLanguage({dispatch}, language) {
  dispatch(types.SET_LANGUAGE, language)
}